#include "stdafx.h"
#include "MysqlConnection.h"
#include "Any.h"
#include "MysqlInitInfo.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

namespace serika
{
	namespace db
	{
		MysqlConnection::MysqlConnection(MysqlConnectionPool& pool)
			: mPool(pool), mMysql(0)
		{
		}
	
		MysqlConnection::~MysqlConnection()
		{
		}
	
		MYSQL* MysqlConnection::GetRawConnection()
		{
			return mMysql;
		}
	
		bool MysqlConnection::Create()
		{
			mMysql = mysql_init(0);
			if (!mMysql)
			{
				return false;
			}
			const Any& initInfo = mPool.GetInitInfo();
			const MysqlInitInfo& mysqlInitInfo = initInfo.Get<MysqlInitInfo>();
			int timeout = mysqlInitInfo.timeout;
			mysql_options(mMysql, MYSQL_OPT_CONNECT_TIMEOUT, reinterpret_cast<const char*>(&timeout));
			MYSQL* m = mysql_real_connect(mMysql,
				mysqlInitInfo.host.c_str(),
				mysqlInitInfo.username.c_str(),
				mysqlInitInfo.password.c_str(),
				mysqlInitInfo.database.c_str(),
				mysqlInitInfo.port, 0, CLIENT_MULTI_STATEMENTS);
			if (!m)
			{
				mysql_close(mMysql);
				return false;
			}
			mysql_set_character_set(mMysql, mysqlInitInfo.encoding.c_str());
			mMysql = m;
	
			return true;
		}
		
		void MysqlConnection::Close()
		{
			mysql_close(mMysql);
		}
	
		bool MysqlConnection::Test()
		{
			return mysql_ping(mMysql) == 0;
		}
	
		bool MysqlConnection::Reconnect()
		{
			this->Close();
			return this->Create();
		}
	}
}
